package com.flitsneak.redis.producer;

import com.flitsneak.common.entity.Info;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/8/10 15:11
 * @description
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/redis")
public class RedisProducer {

    private static final String STREAM_KEY = "good-stream";

    private final ReactiveRedisTemplate<String,String> reactiveRedisTemplate;

    @GetMapping("/sendMessage")
    public String sendMessage() {
        Info info = new Info();
        info.setId(66);
        info.setDes("hello");
        info.setTime(new Date());

        ObjectRecord<String, Info> records = StreamRecords.newRecord()
                .in(STREAM_KEY)
                .ofObject(info)
                .withId(RecordId.autoGenerate());
        reactiveRedisTemplate.opsForStream()
                .add(records)
                .subscribe(a->
                    log.info("redis stream 发送消息：{}",a.getValue())
                );
        return "SUCCESS!";
    }
}
